﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NS.Utilities;
using WechatDAL;
using WechatModel;

namespace BLL
{
    public class MessageBll
    {
        private static readonly W_MessageDal wdal = new W_MessageDal();

        /// <summary>
        /// 公众号发送文本消息
        /// </summary>
        /// <param name="touser"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public bool SendText(string touser, string data)
        {
            return SendMessage(touser, WMessageType.Text, data);
        }

        /// <summary>
        /// 公众号发送新闻列表消息
        /// </summary>
        /// <returns></returns>
        public bool SendNews(string touser, List<W_NewsInfo> news)
        {
            return SendMessage(touser, WMessageType.News, JsonHelper.T2JSON(news));
        }

        /// <summary>
        /// 向用户发送消息
        /// </summary>
        /// <param name="touser">用户的openid</param>
        /// <param name="msgType">消息类型</param>
        /// <param name="data">消息内容</param>
        /// <returns></returns>
        private bool SendMessage(string touser, string msgType, string data)
        {
            string content = "{{\"touser\":\"{0}\",\"msgtype\":\"{1}\",\"{2}\":{{{3}}}}}";
            string body = "";
            if (msgType == WMessageType.Text)
            {
                body = string.Format("\"content\":\"{0}\"", data);
            }
            else if (msgType == WMessageType.Image || msgType == WMessageType.Voice)
            {
                body = string.Format("\"media_id\":\"{0}\"", data);
            }
            else if (msgType == WMessageType.Video)
            {
                body = data;
            }
            else if (msgType == WMessageType.News)
            {
                body = string.Format("\"articles\":{0}", data);
            }
            content = string.Format(content, touser, msgType, msgType, body);
            return wdal.SendMessage(touser, content);
        }

        /// <summary>
        /// 向用户发送模版消息
        /// </summary>
        /// <param name="touser">用户openid</param>
        /// <param name="templateId">在公众平台线上模板库中选用模板获得ID</param>
        /// <param name="data">发送内容</param>
        /// <param name="url">，URL置空，则在发送后，点击模板消息会进入一个空白页面（ios），或无法点击（android）。</param>
        /// <param name="topcolor">顶部颜色，默认为#173</param>
        /// <returns></returns>
        public bool SendTempMessage(string touser, string templateId, string data, string url, string topcolor = "#173177")
        {
            string content = "{\"touser\":\"" + touser + "\",\"template_id\":\"" + templateId + "\", \"url\":\"" + url + "\", \"topcolor\":\"" + topcolor + "\",\"data\":{" + data + "}}";
            return wdal.SendTempMessage(content);
        }
    }
}
